# -*- coding: utf-8 -*- 
'''
Created on 2012-2-20

@author: TOM
'''
from decimal import Decimal
from django.db.models import Q
from django.http import HttpResponse
from django.utils.simplejson import dumps
from django.views.decorators.csrf import csrf_exempt
from website import utils, grids
from website.common import getEmployeId
from website.constant import OFFICE_TEACHER
from website.customercontrol.models import TrainingContract
from website.resourcecontrol.models import Employe, CourseRecord, \
    CourseRealRecord, Employe, CourseRecord, CourseRealRecord, ScheduleRecord, \
    CourseCurrentRecord
import calendar
import datetime
import math

def rewrap_student(student):
    result={}
    result['student_id']=student.id
    result['student_name']=student.name
    return result

renderer='''
    function(value, metaData){
        var results="";
        if(value.length>0){
            metaData.style='background:#FF66CC';
            for(var i=0;i<value.length;i++){
                results+=value[i].student_name+" ";
            }            
        }
        return results;
    }
        '''
#排课查询
@csrf_exempt
def courseschedul_query(request):
    '''
                查询当前用户排课信息----加入session
    '''
    querytime=request.POST.get('querytime',datetime.datetime.now().strftime('%Y-%m-%d'))
    querymode=request.POST.get('querymode','day')
    pct=datetime.datetime.strptime(querytime,'%Y-%m-%d')
    teacher_id=getEmployeId(request)
    if teacher_id is not None:
        if querymode=='month':
            #查询当前用户的当月排课信息
            try:
                fields_conf=[]
                fields_conf.append({'name':'id','type':'string'})
                fields_conf.append({'name':'singledate','type':'string'})
                columns_conf = []
                columns_conf.append({'text': '日期', 'width': 100, 'dataIndex': 'singledate', 'sortable': 'false'})  
                items=[]
                for key in range(8,21):
                    fields_conf.append({'name':'hour'+str(key)})
                    columns_conf.append({'text': str(key)+'点', 'width': 100, 'dataIndex': 'hour'+str(key), 
                                         'sortable': 'false','renderer':renderer}) 
                
                queryset=CourseRecord.objects.filter(teacher=teacher_id,begin_time__month=pct.month,end_time__month=pct.month)
                ct_year=pct.year
                ct_month=pct.month
                for _day in calendar.Calendar().itermonthdays(ct_year, ct_month):
                    if _day==0:
                        continue
                    item={}
                    item['singledate']=str(ct_year)+'-'+str(ct_month)+'-'+str(_day)
                    for key in range(8,21):
                        item['hour'+str(key)]=[] 
                    for qs in queryset:
                        if _day is not qs.begin_time.day:
                            continue
                        student=rewrap_student(qs.student)
                        degree=qs.end_time.hour-qs.begin_time.hour+1
                        for dge in range(degree):
                            if  student  not in item['hour'+str(qs.begin_time.hour+dge)]:
                                item['hour'+str(qs.begin_time.hour+dge)].append(student)  
                    items.append(item)                 
            except Exception ,ex:
                return HttpResponse(dumps({'success':False,'message':str(ex)}))
        else:
            #查询当前用户的当日排课信息
            try:
                fields_conf=[]
                fields_conf.append({'name':'id','type':'string'})
                fields_conf.append({'name':'student_id','type':'string'})
                fields_conf.append({'name':'student_name','type':'string'})
                fields_conf.append({'name':'guardian_name','type':'string'})
#                fields_conf.append({'name':'guardian_phone','type':'string'})
#                fields_conf.append({'name':'guardian_mobile','type':'string'})
                fields_conf.append({'name':'start_time','type':'string'})
                fields_conf.append({'name':'end_time','type':'string'})
                fields_conf.append({'name':'grade_name','type':'string'})
                fields_conf.append({'name':'course_name','type':'string'})
                columns_conf = []
                columns_conf.append({'text': '学生姓名', 'width': 100, 'dataIndex': 'student_name', 'sortable': 'false'})  
                columns_conf.append({'text': '年级', 'width': 100, 'dataIndex': 'grade_name', 'sortable': 'false'}) 
                columns_conf.append({'text': '课程', 'width': 100, 'dataIndex': 'course_name', 'sortable': 'false'}) 
                columns_conf.append({'text': '上课时间', 'width': 100, 'dataIndex': 'start_time', 'sortable': 'false'})  
                columns_conf.append({'text': '下课时间', 'width': 100, 'dataIndex': 'end_time', 'sortable': 'false'})          
                columns_conf.append({'text': '家长姓名', 'width': 100, 'dataIndex': 'guardian_name', 'sortable': 'false'})  
#                columns_conf.append({'text': '家庭电话', 'width': 100, 'dataIndex': 'guardian_phone', 'sortable': 'false'})  
#                columns_conf.append({'text': '家长手机', 'width': 100, 'dataIndex': 'guardian_mobile', 'sortable': 'false'})  
                queryset=CourseRecord.objects.filter(teacher=teacher_id,begin_time__day=pct.day,end_time__day=pct.day)
                items=[]
                for qs in queryset:
                    item={}
                    item['id']=qs.id
                    item['student_id']=qs.student.id
                    item['student_name']=qs.student.name
                    item['guardian_name']=qs.student.guardian_name
                    item['guardian_phone']=qs.student.guardian_phone
                    item['guardian_mobile']=qs.student.guardian_mobile
                    item['start_time']=qs.begin_time.strftime('%H:%M:%S')
                    item['end_time']=qs.end_time.strftime('%H:%M:%S')
                    item['grade_name']=qs.grade.name
                    item['course_name']=qs.course.name
                    items.append(item)
            except Exception ,ex:
                return HttpResponse(dumps({'success':False,'message':str(ex)}))
        return utils.JsonResponse(grids.SimpleGrid().to_grid(fields_conf,items,json_add={'columns':columns_conf}))
    else:
        return HttpResponse(dumps({'success':False,'message':'无排课信息!'}))



#排课管理
@csrf_exempt
def courseschedul_list(request):
    '''
                    查询所有老师排课信息
    '''
    start=request.POST.get('start','0')
    limit=request.POST.get('limit','20')
    choicetime=request.POST.get('choicetime',datetime.datetime.now().strftime('%Y-%m-%d'))
    try:
        starttime=choicetime+' 00:00:00'
        endtime=choicetime+' 23:59:59'
        #TODO#职务为老师
        teachers=Employe.objects.filter(office__in=OFFICE_TEACHER)
        rows=[]
        for teacher in teachers[int(start):int(start) + int(limit)]:
            row={}
            row['teacher_id']=teacher.id
            row['teacher_name']=teacher.name
            for key in range(8,21):
                row['hour'+str(key)]=[]
            records=teacher.record_teacher.filter(begin_time__gte=starttime,end_time__lte=endtime).order_by('begin_time')            
            for record in records:
                student=rewrap_student(record.student)
                degree=record.end_time.hour-record.begin_time.hour+1
                for dge in range(degree):
                    if  student  not in row['hour'+str(record.begin_time.hour+dge)]:
                        row['hour'+str(record.begin_time.hour+dge)].append(student)                
            rows.append(row)
    except Exception, ex:
        print ex
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,rows,teachers.count()))

@csrf_exempt
def courseschedul_save(request):
    teacher_id=request.POST.get('teacher_id','')
    student_id=request.POST.get('student_id','')
    choicetime=request.POST.get('choicetime','')
    starttime=request.POST.get('starttime','')
    endtime=request.POST.get('endtime','')
    grade_id=request.POST.get('grade_id','')
    course_id=request.POST.get('course_id','')
    study_type_id=request.POST.get('study_type_id','')    
    try:
        CourseRecord.objects.create(student_id=student_id,teacher_id=teacher_id,grade_id=grade_id,
                                    course_id=course_id,study_type=study_type_id,
                                    begin_time=datetime.datetime.strptime(choicetime+' '+starttime,'%Y-%m-%d %H:%M'),
                                    end_time=datetime.datetime.strptime(choicetime+' '+endtime,'%Y-%m-%d %H:%M'))
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def courseschedul_del(request):
    try:
        courseschedul_id=request.POST.get('id','')
        CourseRecord.objects.get(id=courseschedul_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))
    
#教师当日排课信息
@csrf_exempt
def teacher_day_course(request):
    teacher=request.POST.get('teacher_id','')
    choicetime=request.POST.get('choicetime',datetime.datetime.now().strftime('%Y-%m-%d'))
    try:
        starttime=choicetime+' 00:00:00'
        endtime=choicetime+' 23:59:59'
        queryset=CourseRecord.objects.filter(teacher=teacher,begin_time__gte=starttime,end_time__lte=endtime);
        items=[]
        for qs in queryset:
            item={}
            item['id']=qs.id
            item['student_id']=qs.student.id
            item['student_name']=qs.student.name
            item['start_time']=qs.begin_time.strftime('%H:%M:%S')
            item['end_time']=qs.end_time.strftime('%H:%M:%S')
            item['guardian_name']=qs.student.guardian_name
            item['guardian_phone']=qs.student.guardian_phone
            item['guardian_mobile']=qs.student.guardian_mobile            
            item['grade_name']=qs.grade.name
            item['course_name']=qs.course.name
            items.append(item)
    except Exception, ex:
        print ex  
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,items))


#学生当日排课信息
@csrf_exempt
def student_course_hour(request):
    student_id=request.POST.get('student_id','')
    #学生课程明细
    try:
        #学生合同为有效的合同明细
        #queryset=TrainingContract.objects.filter(student=student_id,state=1).order_by('-begin_time')[0].contractdetail_contract.all()
        queryset=CourseCurrentRecord.objects.filter(student=student_id)
        items=[]
        for qs in queryset:
            item={}
            item['grade_id']=qs.grade.id
            item['grade_name']=qs.grade.name
            item['course_id']=qs.course.id
            item['course_name']=qs.course.name
            item['course_times']=int(qs.course_times)-int(qs.use_course_times)
            item['study_type_id']=qs.study_type
            item['study_type']=qs.get_study_type_display()
            items.append(item)
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':'无此学生有效信息!'}))
    return HttpResponse(dumps({'success':True,'message':items}))


#课时真实记录
@csrf_exempt
def course_real_record_list(request):
    start=request.POST['start']
    limit=request.POST['limit']
    company_id=request.POST.get('company_id','')
    student_id=request.POST.get('student_id','')
    state=request.POST.get('state','')
    student_manager_id=request.POST.get('student_manager_id','')
    teacher_id=request.POST.get('teacher_id','')
    
    q=Q()
    if student_id<>'':
        q &=Q(student=student_id)
    if state<>'':
        q &=Q(state=state)
    if company_id<>'':
        q &=Q(company=company_id)
    if teacher_id<>'':
        q &=Q(teacher=teacher_id)
    if student_manager_id<>'':
        q &=Q(student_manager=student_manager_id)
    
    
    queryset=CourseRealRecord.objects.filter(q).extra(order_by=['-create_time'])
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,
        list(queryset[int(start):int(start) + int(limit)].values('id','create_time','begin_time','end_time','state','course_hour',
            'course_id','course__name','grade_id','grade__name','attend','study_type','remark','company_id','company__cn_name','student_id','student__name','teacher_id',
            'teacher__name','student_manager_id','student_manager__name','auditor_id','auditor__name','szjy_id','szjy__name')),queryset.count()))
    
@csrf_exempt
def course_real_record_get(request):
    # 获取指定ID课时
    cid=request.POST.get('id','')
    results=CourseRealRecord.objects.filter(id=cid).values('id','state');
    return utils.JsonResponse(dumps(list(results)))



@csrf_exempt
def course_real_record_save(request):
    record_id=request.POST.get('id','')
    create_time=request.POST.get('create_time','')
    course_id=request.POST.get('course_id','')
    study_type=request.POST.get('study_type','')
    student_id=request.POST.get('student_id','')
    grade_id=request.POST.get('grade_id','')
    begin_time=request.POST.get('begin_time','')
    end_time=request.POST.get('end_time','')
    course_hour=float(request.POST.get('course_hour','1')) # 托管课程,课时数据为1 
    attend=request.POST.get('attend','')
    state=1
    remark=request.POST.get('remark','')
    company_id=request.POST.get('company_id','')
    teacher_id=request.POST.get('teacher_id','')
    student_manager_id=request.POST.get('student_manager_id','')
    szjy_id=request.POST.get('szjy_id','')
    #auditor_id=request.POST.get('auditor_id','')
    
    # 校验课时数
    try:
        cq=Q(student=student_id,grade=grade_id,course=course_id,study_type=study_type)
        courseCurrent=CourseCurrentRecord.objects.get(cq)
        if float(courseCurrent.course_times-courseCurrent.use_course_times)<float(course_hour):
            return HttpResponse(dumps({'success':False,'message':'保存异常::::::当前学生课时数不足 '+course_hour+'课时!<font color=red>请检查[学生对应年级、课时、学生方式、剩余课时数]</font>'}))
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':'保存异常::::::'+str(ex)+'<font color=red>请检查[学生对应年级、课时、学生方式、剩余课时数]</font>'}))
    
    
    try:
        if record_id=='':
            CourseRealRecord.objects.create(create_time=create_time,study_type=study_type,
                                            begin_time=begin_time,end_time=end_time,
                                            course_hour=course_hour,attend=attend,state=state,remark=remark,
                                            course_id=course_id,student_id=student_id,grade_id=grade_id,
                                            company_id=company_id,teacher_id=teacher_id,student_manager_id=student_manager_id,szjy_id=szjy_id
                                            )
            
        else:
            record=CourseRealRecord.objects.get(id=record_id)
            record.create_time=create_time
            record.course_id=course_id
            record.study_type=study_type
            record.student_id=student_id
            record.grade_id=grade_id
            record.begin_time=begin_time
            record.end_time=end_time
            record.course_hour=course_hour
            record.attend=attend
            record.state=state
            record.remark=remark
            record.company_id=company_id
            record.teacher_id=teacher_id
            record.student_manager_id=student_manager_id
            record.szjy_id=szjy_id
            record.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

@csrf_exempt
def course_real_record_update_state(request):
    #审核
    record_id=request.POST.get('id','')
    state=request.POST.get('state','')
    remark=request.POST.get('remark','')
    employe_id=getEmployeId(request) ;
    
    try:
        record=CourseRealRecord.objects.get(id=record_id)
        #修改当前课时
        if state=='2':
            ccr = CourseCurrentRecord.objects.get(student=record.student_id,grade=record.grade_id,course=record.course_id,study_type=record.study_type)
            #ccr.course_times=Decimal(ccr.course_times) - Decimal(record.course_hour)
            ccr.use_course_times=Decimal(ccr.use_course_times)+Decimal(record.course_hour)
            ccr.save()
            
        record.state=state
        record.remark=remark
        record.auditor_id=employe_id
        record.save()
    except Exception,ex:
        #return HttpResponse(dumps({'success':False,'message':str(ex)}))
        return HttpResponse(dumps({'success':False,'message':'课时审核失败,请检查课时记录数据[年级,课程,学习方式]与合同数据是否一致!'+str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))


@csrf_exempt
def course_real_record_del(request):
    try:
        ids=request.POST.get('ids','')
        if ids <> '':
            ids=ids.rstrip(',').split(',')
            for record_id in ids:
                CourseRealRecord.objects.get(id=record_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))





#日程安排
@csrf_exempt
def schedule_list(request):
#    data=[{
#            "id"     : "111",
#            "title"  : "Lunch with Matt",
#            "start"   : '2012-01-12 12:00:00',
#            "end"     : '2012-03-14 13:30:00',
#            "loc"   : "Chuy's!",
#            "url"   : "http://chuys.com",
#            "notes"  : "Order the queso",
#            "rem"   : "15",
#            'ad':''
#    }]
    startDate=request.POST.get('startDate','')
    endDate=request.POST.get('endDate','')
    if(startDate =='' and endDate ==''):
        return HttpResponse(dumps({}))
    queryset=ScheduleRecord.objects.filter(start__gte=startDate.replace('T',' '),end__lte=endDate.replace('T',' '))
    return utils.JsonResponse(grids.SimpleGrid().to_grid(None,list(queryset.values())))


#日程安排
@csrf_exempt
def schedule_save(request):
    schedule_id=request.POST.get('id','')
    title=request.POST.get('title','')
    start=request.POST.get('start','')
    end=request.POST.get('end','')
    loc=request.POST.get('loc','')
    url=request.POST.get('url','')
    notes=request.POST.get('notes','')
    rem=request.POST.get('rem','')
    ad=request.POST.get('ad','')
    try:
        if ad=='true':
            ad=True
        else:
            ad=False
        if schedule_id=='':
            ScheduleRecord.objects.create(title=title,start=start.replace('T',' '),end=end.replace('T',' '),loc=loc,url=url,notes=notes,rem=rem,ad=ad)
        else:
            schedule=ScheduleRecord.objects.get(id=schedule_id)
            schedule.title=title
            schedule.start=start.replace('T',' ')
            schedule.end=end.replace('T',' ')
            schedule.loc=loc
            schedule.url=url
            schedule.notes=notes
            schedule.rem=rem
            schedule.ad=ad
            schedule.save()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'成功！'}))

#日程安排
@csrf_exempt
def schedule_del(request):
    schedule_id=request.POST.get('id','')
    try:
        ScheduleRecord.objects.get(id=schedule_id).delete()
    except Exception,ex:
        return HttpResponse(dumps({'success':False,'message':str(ex)}))
    return HttpResponse(dumps({'success':True,'message':'删除成功！'}))

if __name__=="__main__":
    print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    print "2012-03-16T00:00:00".replace("T", " ")
    #itermonthdates   --itermonthdays  --itermonthdays2(星期 0)

#    print datetime.datetime.strptime('2012-02-21 00:00:00','%Y-%m-%d %H:%M:%S')
#    dd=datetime.datetime.strptime('2012-02-21 00:00:00','%Y-%m-%d %H:%M:%S')
#    print dd,datetime.datetime.now().strftime('%Y-%m-%d')
#    month = calendar.HTMLCalendar().formatmonth(2012,4)
#    print month
    
    
#排课动态列生成(暂不用)
#@csrf_exempt
#def courseschedul_list(request):
#    start=request.POST['start']
#    limit=request.POST['limit']
#
#    try:
#        fields_conf=[]
#        fields_conf.append({'name':'teacher_id','type':'string'})
#        fields_conf.append({'name':'teacher_name','type':'string'})
#        fields_conf.append({'name':'cn_name','type':'string'})
#        columns_conf = []
##        columns_conf.append({"text": "校区名称(中文)", "width": 100, "dataIndex": "id", "sortable": "false","renderer":
##            "function(value,metaData,record){metaData.style='background:red';return value}"})
#        columns_conf.append({"text": "校区名称(中文)", "width": 100, "dataIndex": "cn_name", "sortable": "false"})        
#    except Exception,ex:
#        pass
#    
#    queryset=Company.objects.all();
#    return utils.JsonResponse(grids.SimpleGrid().to_grid(fields_conf,
#        list(queryset[int(start):int(start) + int(limit)].values('id','cn_name')),queryset.count(),{'columns':columns_conf}))

